package com.hy.thread;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.push.model.v20160801.PushRequest;
import com.aliyuncs.push.model.v20160801.PushResponse;
import com.hy.config.ConfigurationUtils;
import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class IOSPushThread implements Runnable{
    protected final Logger logBase = LoggerFactory.getLogger(IOSPushThread.class);

    private static final String accessKeyId = "LTAIO8LAhxifzmyl";
    private static final String accessKeySecret = "RPhCntjfp5XugMc56eypDgmo3yIgPv";
    private static final Long androidAppKey = 25235552L;
//    private static final Long iosAppKey = 24897025L;

    private String text;
    private String title;
    private List<String> tokens;
    private List<String> deviceIdList;
    private String certName;
    private String certPwd;
    private String isProduction;

    public IOSPushThread(String text, List<String> tokens) {
        this.text = text;
        this.tokens = tokens;
    }

    public IOSPushThread(String text, String title, List<String> deviceIdList) {
        this.text = text;
        this.title = title;
        this.deviceIdList = deviceIdList;
    }

    public IOSPushThread(String text, String title, List<String> tokens, List<String> deviceIdList) {
        this.text = text;
        this.title = title;
        this.tokens = tokens;
        this.deviceIdList = deviceIdList;
    }

    public void getPlatform(){
        String platform = ConfigurationUtils.getString("project.environment");
        if("production".equals(platform)){
            certName = ConfigurationUtils.getString("ios_push_cert_name_release");
            certPwd = ConfigurationUtils.getString("ios_push_cert_pwd_release");
            isProduction = ConfigurationUtils.getString("ios_push_is_production_release");
        }else{
            certName = ConfigurationUtils.getString("ios_push_cert_name_debug");
            certPwd = ConfigurationUtils.getString("ios_push_cert_pwd_debug");
            isProduction = ConfigurationUtils.getString("ios_push_is_production_debug");
        }
        System.out.println(platform+" "+certName +" " + certPwd + " " + isProduction );
    }

    public void iosPush(){
        int badge =1;//图标小红圈的数值
        String sound = "default";//铃音

        String certificatePath = IOSPushThread.class.getClassLoader().getResource(certName).getPath();
        String certificatePassword = certPwd;//此处注意导出的证书密码不能为空因为空密码会报错
        Boolean production = isProduction.equals("0") ? false : true ;
        System.out.println("certificatePath:"+certificatePath);
        try {
            boolean sendCount = tokens.size() > 1 ? false : true;

            PushNotificationPayload payLoad = new PushNotificationPayload();
            payLoad.addAlert(text); // 消息内容
            payLoad.addBadge(badge); // iphone应用图标上小红圈上的数值

            if (!StringUtils.isBlank(sound)) {
                payLoad.addSound(sound);//铃音
            }
            PushNotificationManager pushManager = new PushNotificationManager();
            //true：表示的是产品发布推送服务 false：表示的是产品测试推送服务
            pushManager.initializeConnection(new AppleNotificationServerBasicImpl(certificatePath, certificatePassword, production));
            List<PushedNotification> notifications = new ArrayList<PushedNotification>();
            // 发送push消息
            if (sendCount) {
                Device device = new BasicDevice();
                device.setToken(tokens.get(0));
                PushedNotification notification = pushManager.sendNotification(device, payLoad, true);
                notifications.add(notification);
            } else{
                List<Device> device = new ArrayList<Device>();
                for (String token : tokens) {
                    device.add(new BasicDevice(token));
                }
                notifications = pushManager.sendNotifications(payLoad, device);
            }
            pushManager.stopConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void androidPush(){
        StringBuilder deviceIdsSB = new StringBuilder();
        for (String deviceId : deviceIdList) {
            if(deviceIdsSB.length() > 0){
                deviceIdsSB.append(",");
            }
            deviceIdsSB.append(deviceId);
        }

        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",
                accessKeyId,      // The AccessKey ID of the RAM account
                accessKeySecret); // The AccessKey Secret of the RAM account
        IAcsClient client = new DefaultAcsClient(profile);
        PushRequest request = new PushRequest();
        request.setAppKey( androidAppKey); //Your AppKey

        request.setTarget("DEVICE");
        request.setTargetValue(deviceIdsSB.toString());
        request.setPushType("NOTICE");
        request.setDeviceType("ANDROID");
        request.setStoreOffline(true);
        request.setAndroidNotificationChannel("goodedu_channel_id");

        // 推送配置
        request.setTitle(title);
        request.setBody(text);
        try {
            PushResponse response = client.getAcsResponse(request);
            System.out.println("requestId="+response.getRequestId());
            System.out.println("messageId="+response.getMessageId());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        if(StringUtils.isNotBlank(text)){
            if(!tokens.isEmpty()) {//是否有iOS用户需要推送
                getPlatform();
                iosPush();
            }
            if(!deviceIdList.isEmpty()) {//是否有android用户需要推送
                androidPush();
            }
        }
    }

    public static void main(String[] args) {
        String deviceIds = "d481b022bcfa49f88f5562d762584047";
//        String deviceIds = "2700fa7bc93449d0979135130b8ac713,946d5ede64a84a52a831142436d29687,362af16c89ba444daa23cfa1c4ce312e,91c9d86067894f7eba09484dd6bb96d6";
//goodedu_channel


        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",
                accessKeyId,      // The AccessKey ID of the RAM account
                accessKeySecret); // The AccessKey Secret of the RAM account
        IAcsClient client = new DefaultAcsClient(profile);
        PushRequest request = new PushRequest();
        request.setAppKey( androidAppKey); //Your AppKey

        request.setTarget("DEVICE");
        request.setTargetValue(deviceIds);
//        request.setTarget("ALL");
//        request.setTargetValue("ALL");
        request.setPushType("NOTICE");
        request.setDeviceType("ANDROID");

        // 推送配置
        request.setTitle("测试推送标题");
        request.setBody("测试推送内容");

        //android推送
        request.setAndroidOpenType("NONE"); //点击通知后动作 "APPLICATION" : 打开应用 默认值 "ACTIVITY" : 打开AndroidActivity "URL" : 打开URL "NONE" : 无跳转
        request.setAndroidNotificationChannel("goodedu_channel_id");
        request.setStoreOffline(true);

        try {
            PushResponse response = client.getAcsResponse(request);
            System.out.println("requestId="+response.getRequestId());
            System.out.println("messageId="+response.getMessageId());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
